package com.baidu.ota.impl;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Locale;

/**
 * 等于Android 6.0(API=23)的版本
 */
public class RecoverySystemEQ23 extends RecoverySystem {
    private static final String TAG = "RecoverySystem";

    private static File RECOVERY_DIR = new File("/cache/recovery");
    private static File COMMAND_FILE = new File(RECOVERY_DIR, "command");
    private static File UNCRYPT_FILE = new File(RECOVERY_DIR, "uncrypt_file");
    private static File LOG_FILE = new File(RECOVERY_DIR, "log");

    @Override
    public String installSystemOnNextBoot(Context context, File file) {
        try {
            installPackage(file);
        } catch (Exception e) {
            return e.toString();
        }
        return "";
    }

    private void installPackage(File packageFile) throws Exception {
        String filename = packageFile.getCanonicalPath();

        FileWriter uncryptFile = new FileWriter(UNCRYPT_FILE);
        try {
            uncryptFile.write(filename + "\n");
        } finally {
            uncryptFile.close();
        }
        Log.w(TAG, "!!! REBOOTING TO INSTALL " + filename + " !!!");

        if (filename.startsWith("/data/")) {
            filename = "@/cache/recovery/block.map";
        }

        final String filenameArg = "--update_package=" + filename;
        final String localeArg = "--locale=" + Locale.ROOT.toString();

        bootCommand(filenameArg, localeArg);
    }

    private void bootCommand(String... args) throws IOException {
        RECOVERY_DIR.mkdirs();
        COMMAND_FILE.delete();
        LOG_FILE.delete();

        FileWriter command = new FileWriter(COMMAND_FILE);
        try {
            for (String arg : args) {
                if (!TextUtils.isEmpty(arg)) {
                    command.write(arg);
                    command.write("\n");
                }
            }
        } finally {
            command.close();
        }
    }
}
